package com.xxc.response.interceptor

import com.xxc.common.anotation.POKO
import com.xxc.response.anotation.OriginResponse
import com.xxc.response.anotation.ResponseResult
import com.xxc.response.constant.RESPONSE_RESULT
import org.springframework.web.method.HandlerMethod
import org.springframework.web.servlet.HandlerInterceptor
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

@POKO
class ResponseResultInterceptor:HandlerInterceptor {

    override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {
        if(handler is HandlerMethod)
        {
            // 如果有@OriginResponse注解将不拦截
            if(handler.method.isAnnotationPresent(OriginResponse::class.java))
                return true
            //如果调用的Controller的方法或Controller类上使用了ResponseResult注解，
            // 则将响应类型放入请求
            if(handler.beanType.isAnnotationPresent(ResponseResult::class.java)
                    || handler.method.isAnnotationPresent(ResponseResult::class.java))
            {
                var type:ResponseResult? = handler.beanType.getAnnotation(ResponseResult::class.java)
                if(type == null)
                    type = handler.method.getAnnotation(ResponseResult::class.java)
                request.setAttribute(RESPONSE_RESULT,type!!.value)
            }
        }
        return true
    }

}